/**
 * * tp标记变量要放到htm页面渲染
 */
// var listId = "{$parameter['list_id']}"
// var urlSelectInfoIndex = "__CONTROLLER__/SelectInfoIndex"
// var urlGetResultInfo = "__CONTROLLER__/getResultInfo"
// var urlSaveVoteData = "__CONTROLLER__/SaveVoteData"
// var urlGetIsUser = "__CONTROLLER__/getIsUser"

/**
 * * 复选框限制选择
 * @param {dom} name 复选框组名
 * @param {Number} num  限制可选择数
 * bug 只能选择取消，不能自动取消最后选择的选项
 * TODO 用队列判断，自动取消开始选择的选项
 */
function choiceLimit(name, num) {
  var choicearr = document.getElementsByName(name);
  var a = 0;
  for (var i = 0; i < choicearr.length; i++) {
    if (choicearr[i].checked) {
      a += 1;
    }
  }
  if (a > num) {

    // for (var i = 0; i < choicearr.length; i++) {
    //   if (!choicearr[i].checked) {
    //     choicearr[i].disabled = 'disabled'
    //   }
    // }
    $.toptip("\u6700\u591A\u53EA\u80FD\u9009" + num + "\u4E2A", 800);
    return false;
  } else {
    return true;
    for (var i = 0; i < choicearr.length; i++) {
      choicearr[i].removeAttribute('disabled');
    }
  }
}

$.ajax({
  type: "POST",
  url: urlGetResultInfo,
  data: {
    list_id: listId
  },
  dataType: "json",
  success: function success(response) {

    // 已投票
    if (response.errcode && response.errcode === 0) {

      console.dir(response);
      // 投票结果
      $.ajax({
        type: "POST",
        url: urlGetResultInfo,
        data: {
          "list_id": listId
        },
        dataType: "json",
        success: function success(response) {

          var voteItem = '';
          console.log(response);

          if (response.data.title && response.data.title.length > -1) {

            for (var i = 0; i < response.data.title.length; i++) {
              var optionsTmp = '';
              voteItem += "<div class=\"topic-wrapper\">\n                      <div class=\"weui-cells__title\" data-id=\"" + response.data.title[i].id + "\" data-topic=\"" + response.data.title[i].title + "\">\n                        <span >" + response.data.title[i].title + "</span>\n                        <span class=\"choice\">[\u6700\u591A\u53EF\u9009" + (response.data.title[i].choice || 1) + "\u9879]</span>\n                      </div>\n                      <div class=\"weui-cells weui-cells_checkbox\">";
              for (var j = 0; j < response.data.title[i].options.length; j++) {

                var tmpOptionItem = response.data.title[i].options[j];
                optionsTmp = "<label class=\"weui-cell weui-check__label\" for=\"s" + tmpOptionItem.id + "\">\n                        <div class=\"weui-cell__hd\">\n                          <input type=\"checkbox\" class=\"weui-check\" name=\"vote" + response.data.title[i].id + "\" data-select-num=\"" + response.data.title[i].choice + "\" id=\"s" + tmpOptionItem.id + "\" " + (tmpOptionItem.selected === 1 ? "checked" : '') + " data-selected=\"" + tmpOptionItem.selected + "\" data-title_id=\"" + tmpOptionItem.title_id + "\" data-name=\"" + tmpOptionItem.options_content + "\">\n                          <i class=\"weui-icon-checked\"></i>\n                        </div>\n                        <div class=\"weui-cell__bd\">\n                          <p>" + tmpOptionItem.options_content + "</p>\n                        </div>\n                        <div class=\"weui-cell__ft poll-result\">\n                          <p class=\"poll-box\"><span class=\"poll\">" + tmpOptionItem.num + "</span>\u7968</p>\n                        </div>\n                      </label>";
                voteItem += optionsTmp;
              }
              voteItem += "</div></div>";
            }
            var htmlBtn = "<section class=\"btn-submit\">\n                    <a href=\"javascript:;\" class=\"weui-btn weui-btn_primary\" id=\"vote\">\u4FEE\u6539\u6295\u7968</a>\n                    <a href=\"javascript:;\" class=\"weui-btn weui-btn_plain-primary\" id=\"show-result\">\u663E\u793A\u7ED3\u679C</a>\n                  </section>";
            voteItem += htmlBtn;
            $('.vote-box').append(voteItem);

            // $('#vote').addClass('weui-btn_disabled')
            // $('#vote').off('click')
            $('#vote').text('修改投票');

            $('.vote-box').on('click', '.topic-wrapper input', function () {
              $(this).each(function () {
                console.log($(this).attr('name'));
                var isChecked = choiceLimit($(this).attr('name'), $(this).data('select-num'));
                console.log($(this).data('select-num'));
                if (!isChecked) {
                  $(this).removeAttr('checked');
                }
              });
            });
          }
        }
      });
    } else {

      // 未投票
      var voteItem = '';
      if (response.data.title && response.data.title.length > -1) {

        for (var i = 0; i < response.data.title.length; i++) {
          var optionsTmp = '';
          voteItem += "<div class=\"topic-wrapper data-topic-box=\"" + response.data.title[i].id + "\">\n                  <div class=\"weui-cells__title\" data-id=\"" + response.data.title[i].id + "\" data-topic=\"" + response.data.title[i].title + "\">\n                    <span >" + response.data.title[i].title + "</span>\n                    <span class=\"choice\">[\u6700\u591A\u53EF\u9009" + (response.data.title[i].choice || 1) + "\u9879]</span>\n                  </div>\n                  <div class=\"weui-cells weui-cells_checkbox\">";
          for (var j = 0; j < response.data.title[i].options.length; j++) {

            var tmpOptionItem = response.data.title[i].options[j];
            optionsTmp = "<label class=\"weui-cell weui-check__label\" for=\"s" + tmpOptionItem.id + "\">\n                <div class=\"weui-cell__hd\">\n                  <input type=\"checkbox\" class=\"weui-check\" name=\"vote" + response.data.title[i].id + "\" data-select-num=\"" + response.data.title[i].choice + "\" id=\"s" + tmpOptionItem.id + "\" " + (tmpOptionItem.selected === 1 ? "checked" : '') + " data-title_id=\"" + tmpOptionItem.title_id + "\" data-name=\"" + tmpOptionItem.options_content + "\" data-index=\"" + j + "\">\n                  <i class=\"weui-icon-checked\"></i>\n                </div>\n                <div class=\"weui-cell__bd\">\n                  <p>" + tmpOptionItem.options_content + "</p>\n                </div>\n                <div class=\"weui-cell__ft poll-result\">\n                  <p class=\"poll-box\"><span class=\"poll\"></span>\u7968</p>\n                </div>\n              </label>";
            voteItem += optionsTmp;
          }
          voteItem += "</div></div>";
        }
        var htmlBtn = "<section class=\"btn-submit\">\n                <a href=\"javascript:;\" class=\"weui-btn weui-btn_primary\" id=\"vote\">" + (response.data.checked == 1 ? '修改投票' : '投票') + "</a>\n                <a href=\"javascript:;\" class=\"weui-btn weui-btn_plain-primary\" id=\"show-result\">\u663E\u793A\u7ED3\u679C</a>\n              </section>";
        voteItem += htmlBtn;
        $('.vote-box').append(voteItem);
      }

      var checkedArrIndex = [];
      // dom限制复选框选择个数
      $('.vote-box').on('click', '.topic-wrapper input', function (evt) {
        $(this).each(function (index, item) {
          console.log($(item));
          var isChecked = choiceLimit($(this).attr('name'), $(this).data('select-num'));
          if (!isChecked) {
            $(this).removeAttr('checked');
          }
          // TODO 1.组装数据，用队列实现
          // checkedArrIndex.push({
          //   "vote": $(item).attr('name'),
          //   "selected": []
          // })
          // if($(item).is(':checked') && checkedArrIndex.length <= $(item).data('select-num')) {
          //   checkedArrIndex.push($(item).data('index'))
          // }
          // console.log('item', item)
          // console.log('index', index)
          // console.log($(this).is(':checked'))

          // 队列选择的方式
          // if ($(this).is(':checked')) {

          //   checkedArrIndex.push($(this).data('index'))
          // }

          // console.log(checkedArrIndex)
          // console.log($(this).data('select-num'))
          // // bug 点击选项闪屏
          // // choiceLimit($(this).attr('name'), $(this).data('select-num'))
          // if ($(this).is(':checked') && checkedArrIndex.length > $(this).data('select-num')) {

          //   let queue = checkedArrIndex.shift()
          //   let $name = $(item).attr('name')
          //   if ($(`input[name=${$name}]input[data-index=${queue}]`).is(':checked')) {
          //     $(evt.currentTarget.parent)
          //     $(`input[name=${$name}][data-index=${queue}]`).removeAttr('checked')
          //   } else {

          //     $(`input[name=${$name}][data-index=${queue}]`).prop('checked', 'checked')
          //   }
          // } else if (!$(this).is(':checked')) {

          //   checkedArrIndex.pop()
          //   Array.from(new Set(checkedArrIndex))
          // }
        });
      });

      // 显示投票结果事件
      $('.vote-box').on('click', '#show-result', function () {
        $.ajax({
          type: "POST",
          url: urlGetResultInfo,
          data: {
            "list_id": listId
          },
          dataType: "json",
          success: function success(response) {
            console.log(response);
            var pollResult = [];

            if (response.data.title && response.data.title.length > -1) {

              for (var _i = 0; _i < response.data.title.length; _i++) {

                if (response.data.title[_i] && response.data.title[_i].options.length > -1) {

                  for (var _j = 0; _j < response.data.title[_i].options.length; _j++) {

                    pollResult.push(response.data.title[_i].options[_j].num);
                  }
                }
              }
            }
            console.log(pollResult);

            // 显示投票结果
            $.map($('.vote-box .topic-wrapper .poll-result').find('.poll'), function (item, itemIndex) {
              console.log(item);
              $(item).text(pollResult[itemIndex]);
            });
          },
          error: function error() {
            $.toast('请先投票');
          }
        });
      });
    }

    // TODO 原投票代码

    // 显示结果事件
    $('.vote-box').on('click', '#show-result', function (evt) {
      var $this = $(this);
      $(this).parent().prevAll().find('.poll-result').toggle(10, function () {});
      var textResult = $(this).text();
      $this.text(textResult === "显示结果" ? "隐藏结果" : "显示结果");
      $this.animate({});
    });

    $.ajax({
      type: "POST",
      url: urlGetIsUser,
      data: {
        "list_id": listId
      },
      dataType: "json",
      success: function success(response) {
        console.log(response);
        console.log(response.data.is_poster);
        if (response.data.is_poster == 1) {
          $('#show-result').css('display', 'block');
        }
      }
    });
  },
  complete: function complete(response) {
    $('#vote').on('click', function () {
      var postData = [];
      //获取投票选项
      console.log($('.vote-box .topic-wrapper'));
      $.map($('.vote-box .topic-wrapper'), function (topic, topicIndex) {
        var tmp = [];
        var itemData = [];

        $.map($(topic).find('input'), function (item, itemIndex) {

          if ($(item).is(':checked')) {
            itemData.push({
              "id": $(item).attr('id').replace('s', ''),
              "name": $(item).data('name'),
              "value": itemIndex,
              "title_id": $(item).data('title_id')
            });
          }
        });
        postData.push({
          "list_id": listId,
          "data": itemData
        });
      });
      console.log(postData);
      $.ajax({
        type: "POST",
        url: urlSaveVoteData,
        data: {
          "data": postData
        },
        dataType: "json",
        success: function success(response) {
          // TODO
          console.log(response);
          if (response.errcode === 0) {
            $.toast('投票成功', 1000);
            // $('#vote').addClass('weui-btn_disabled')
            // $('#vote').off('click')
            $('#vote').text('修改投票');

            // 投票结束取消复选框选择事件
            // $('.vote-box').off('click', 'input')

            // fixed 修复投票后页面选项还可以修改的问题
            // 允许再次修改
            // $('input[type=checkbox]').each(function () {
            //   console.log($(this))
            //   $(this).prop('disabled', 'disabled')
            // })
          }
        }
      });
    });
  }
});

$.ajax({
  type: "POST",
  url: urlList.getAppJssdkInfo,
  // url: 'https://herb.yicanfan123.com/mobile/api_get_signpackage.php',
  data: {
    url: window.location.href.split('/list_id')[0] || postData.locationUrl
  },
  dataType: "json",
  success: function success(response) {
    console.log(response);
    if (response.data) {
      var jssdk = response.data;
      console.log(jssdk);
      wx.config({
        debug: false,
        appId: jssdk.appId,
        timestamp: jssdk.timestamp,
        nonceStr: jssdk.nonceStr,
        signature: jssdk.signature,
        jsApiList: [
        // 所有要调用的 API 都要加到这个列表中
        'chooseImage', 'uploadImage', 'onMenuShareTimeline', 'hideOptionMenu', 'showMenuItems', 'onMenuShareAppMessage']
      });
      wx.ready(function () {
        wx.onMenuShareAppMessage({
          title: "", // 分享标题
          desc: "", // 分享描述
          link: "", // 分享链接
          imgUrl: '', // 分享图标
          type: '', // 分享类型,music、video或link，不填默认为link
          dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
          success: function success() {
            weui.toast('分享成功');
          },
          cancel: function cancel() {}
        });
        wx.onMenuShareTimeline({
          title: "", // 分享标题
          desc: "", // 分享描述
          link: "", // 分享链接
          imgUrl: '',
          success: function success() {
            weui.toast('分享成功');
          },
          cancel: function cancel() {}
        });
      });
    }
  }
});